package TCP;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private static Socket socket;
    public Client(Socket socket){
        Client.socket = socket;
    }

    public  void start(){
        try {
            OutputStream os = socket.getOutputStream();
            InputStream is = socket.getInputStream();

            DataOutputStream dos = new DataOutputStream(os);
            DataInputStream dis = new DataInputStream(is);

            //发送数据
            Scanner scanner = new Scanner(System.in);
            while (true){
                System.out.println("请输出:");
                String str = scanner.nextLine();
                if ("exit".equals(str)){
                    System.out.println("退出成功!!!!");
                    dis.close();
                    dos.close();
                    socket.close();
                    break;
                }
                dos.writeUTF(str);
                dos.flush();

                //接受返回来的数据
                try {
                    String ret = dis.readUTF();
                    System.out.println("服务端返回的数据: "+ret);
                } catch (IOException e) {
                    System.out.println(socket.getRemoteSocketAddress()+" 本机已离线");
                    dis.close();
                    dos.close();
                    socket.close();
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",8888);
        Client client = new Client(socket);
        client.start();

    }
}
